using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PoolManager : Singleton<PoolManager>
{
    [SerializeField] private Transform parentTf;
    [SerializeField] private Pool[] propPools;
    [SerializeField] private Pool[] itemPools;
 
    private Dictionary<GameObject, Pool> poolDic = new Dictionary<GameObject, Pool>();

    protected override void Awake()
    {
        base.Awake();

        Init(propPools);
        Init(itemPools);
    }

    private void OnDestroy() {
        CheckRunTimeSize(propPools);
        CheckRunTimeSize(itemPools);
    }
    
    private void CheckRunTimeSize(Pool[] pools)
    {
        foreach(Pool pool in pools)
        {
            if(poolDic[pool.prefab].queue.Count > pool.size)
            {
                Debug.LogWarning($"预制件{pool.prefab.name}初始大小{pool.size}超过实际大小{poolDic[pool.prefab].queue.Count}");
            }
        }
    }

    private void Init(Pool[] pools)
    {
        foreach(Pool pool in pools)
        {
            Prepare(pool);
        }
    }

    private void Prepare(Pool pool)
    {
        GameObject parent = new GameObject(pool.prefab.name);
        parent.transform.SetParent(parentTf);
        pool.queue = new Queue<GameObject>();

        for(int i=0; i<pool.size; i++)
        {
            GameObject go = Instantiate(pool.prefab, parent.transform);
            go.SetActive(false);
            pool.queue.Enqueue(go);
        }

        poolDic.Add(pool.prefab, pool);
    }

    public GameObject ReuseGO(GameObject prefab, Vector3 pos, Quaternion quat)
    {
        GameObject result = null;

        if(!poolDic.ContainsKey(prefab))
        {
            Debug.Log($"该字典不存在该预制件: {prefab.name}");
            return result;
        }

        if(poolDic[prefab].queue.Count > 0 && !poolDic[prefab].queue.Peek().activeSelf)
        {
            result = poolDic[prefab].queue.Dequeue();
        }
        else
        {
            result = Instantiate(prefab);
        }

        poolDic[prefab].queue.Enqueue(result);
        result.transform.position = pos;
        result.transform.rotation = quat;
        result.SetActive(true);

        return result;
    }
}
